const express = require('express')
const router = express.Router()
const {
    insertAdmin,
    checkAdminLogin,
    getAdminList,
    freezeAdmin,
    removeAdmin,
    modifyAdmin
} = require('../../model/mongo')
const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken')

router.get('/list', async (req, res) => {
    const result = {
        code: 200,
        msg: '获取管理员列表',
        data: []
    }
    try {
        result.data = await getAdminList()
    } catch (err) {
        result.code = 400
    }
    res.send(JSON.stringify(result))
})

router.post('/login', async (req, res) => {
    const private_key = fs.readFileSync(path.join(__dirname, '../../key/rsa_private_key.pem'))
    const result = {
        code: 200,
        msg: '',
        data: {}
    }
    try {
        let { msg, author, type, freeze } = await checkAdminLogin(req.body)
        result.msg = msg
        result.data.type = type
        result.data.author = author
        result.data.freeze = freeze
        result.data.token = jwt.sign(req.body, private_key, { algorithm: 'RS256' })
    } catch (err) {
        result.code = 400
        result.msg = err
    }
    res.send(JSON.stringify(result))
})

router.post('/regist', async (req, res) => {
    const result = {
        code: 200,
        msg: '管理员添加成功'
    }
    try {
        if (req.body.type) {
            result.msg = '超级'
        } else {
            result.msg = ''
        }
        result.msg += await insertAdmin(req.body)
    } catch (err) {
        result.code = 400
        result.msg = err
    }
    res.send(JSON.stringify(result))
})

// 冻结管理员
router.post('/freeze', async (req, res) => {
    let { id, bool } = req.body
    let result = {
        code: 200
    }
    if (bool === 'true') {
        bool = true
    }
    if (bool === 'false') {
        bool = false
    }
    result.msg = await freezeAdmin(id, bool)
    res.send(JSON.stringify(result))
})

// 注销管理员
router.post('/remove', async (req, res) => {
    let { id } = req.body
    let result = {
        code: 200
    }
    result.msg = await removeAdmin(id)
    res.send(JSON.stringify(result))
})

// 修改管理员信息
router.post('/modify', async (req, res) => {
    let { id, data } = req.body
    let result = {
        code: 200
    }
    result.msg = await modifyAdmin(id, data)
    res.send(JSON.stringify(result))
})

module.exports = router
